﻿using SqlSugar;

namespace memo.Config
{
    public class DbContext
    {
        public static SqlSugarScope GetInstance()
        {
            return new SqlSugarScope(new ConnectionConfig() {
                ConnectionString = "server=localhost;port=3306;database=memo-demo;uid=root;pwd=1234;CharSet=utf8", //  数据库连接字符串
                DbType = DbType.MySql, //  指定数据库类型
                IsAutoCloseConnection = true, //  自动关闭连接
                InitKeyType = InitKeyType.Attribute,  // 从实体特性读取主键信息
                
                // 配置外部服务
                ConfigureExternalServices = new ConfigureExternalServices() {
                    EntityNameService = (type, entity) => {
                        entity.DbTableName = UtilMethods.ToUnderLine(entity.DbTableName); //  表名转换(驼峰转下划线)
                    },
                    EntityService = (type, column) => {
                        column.DbColumnName = UtilMethods.ToUnderLine(column.DbColumnName); //  字段名转换(驼峰转下划线)
                    },
                }
            },
                configAction =>{
                    // 执行前：输出SQL和参数
                    configAction.Aop.OnLogExecuting = (sql, pars) =>{
                        Console.WriteLine($"-->SQL: {sql}");
                        Console.WriteLine($"参数: {string.Join(", ", pars.Select(p => $"{p.ParameterName}={p.Value}"))}");
                    };

                    // 执行后：输出执行耗时
                    configAction.Aop.OnLogExecuted = (sql, pars) =>{
                        Console.WriteLine($"执行耗时: {configAction.Ado.SqlExecutionTime.TotalMilliseconds}ms");
                        Console.WriteLine();
                    };
                }
            );
        }
        
        
    }
}

